<template>
  <MySplitPanes>
    <pane size="30" min-size="0" max-size="30">
      <div class="my-flex-column w100 h100">
        <station-block-table-menu @table-click="onPlcBlockTableClick"></station-block-table-menu>
      </div>
    </pane>
    <pane>
      <div class="my-flex-column w100 h100">
        <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" label-width="auto" @submit.stop.prevent>
            <el-form-item>
              <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
              <el-button type="primary" icon="ele-Search" @click="onFilter"> 高级查询 </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="my-fill mt8" shadow="never">
          <div class="my-tools-box mb8 my-flex my-flex-between">
            <div>
              <el-button v-auth="'api:industry:work-station:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增
              </el-button>
              <el-button v-auth="'api:industry:work-station:add'" type="primary" icon="ele-View" @click="onLook">
                最新值
              </el-button>
            </div>
            <div>
              <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
                <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
                  @click="state.showQuery = !state.showQuery" />
              </el-tooltip>
            </div>
          </div>

          <el-table ref="tableRef" v-loading="state.loading" :data="state.blockOffsetListData" row-key="id"
            @sort-change="onSortChange" border>
            <el-table-column type="selection" />
            <el-table-column prop="offset" label="偏移量" width="67" show-overflow-tooltip />
            <el-table-column prop="dataType" label="类型" width="100" show-overflow-tooltip align="center">
              <template #default="{ row }">
                <el-tag>{{ convertPLCDataTypeToLabel(row.dataType) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="another" label="标识(唯一)" width="100" show-overflow-tooltip>
              <template #default="{ row }">
                <el-select v-if="isEditing(row)" filterable allow-create v-model="row.another" clearable
                  placeholder="Select" style="width: 240px">
                  <el-option v-for="item in offsetAnthor" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <span v-else>{{ row.another }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述(工艺名称)" width="120" show-overflow-tooltip>
              <template #default="{ row }">
                <el-input v-if="isEditing(row)" v-model="row.description" />
                <span v-else>{{ row.description }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="groupName" label="分组" width="100" show-overflow-tooltip>
              <template #default="{ row }">
                <el-input v-if="isEditing(row)" v-model="row.groupName" />
                <span v-else>{{ row.groupName }}</span>
              </template>
            </el-table-column>

            <el-table-column label="订阅" width="80" align="center" fixed="right">
              <template #default="{ row }">
                <el-switch v-if="auth('api:industry:work-station:set-enable')" v-model="row.isNoticed"
                  :loading="row.loading" :active-value='true' :inactive-value='false' inline-prompt active-text="启用"
                  inactive-text="停用" :before-change="() => onSetNotice(row)" />
                <template v-else>
                  <el-tag type="success" v-if="row.isNoticed">启用</el-tag>
                  <el-tag type="danger" v-else>停用</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="topic" label="主题" width="100" show-overflow-tooltip>
              <template #default="{ row }">
                <el-input v-if="isEditing(row)" v-model="row.topic" />
                <span v-else>{{ row.topic }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" width="100" show-overflow-tooltip>
              <template #default="{ row }">
                <el-input v-if="isEditing(row)" v-model="row.unit" />
                <span v-else>{{ row.unit }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="upper" label="上限" width="100" show-overflow-tooltip>
              <template #default="{ row }">
                <el-input type="number" :precision="2" :step="0.1" v-if="isEditing(row)" v-model="row.upper" />
                <span v-else>{{ row.upper }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="lower" label="下限" width="100" show-overflow-tooltip>
              <template #default="{ row }">
                <el-input type="number" :precision="2" :step="0.1" v-if="isEditing(row)" v-model="row.lower" />
                <span v-else>{{ row.lower }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="currentValue" label="最新值" width="80" align="center" fixed="right"
              show-overflow-tooltip />
            <el-table-column prop="sort" label="排序" width="100" align="center" sortable="custom" show-overflow-tooltip>
              <template #default="{ row }">
                <el-input type="number" v-if="isEditing(row)" v-model="row.sort" />
                <span v-else>{{ row.sort }}</span>
              </template></el-table-column>
            <el-table-column label="状态" width="80" align="center" fixed="right">
              <template #default="{ row }">
                <el-switch v-if="auth('api:industry:work-station:set-enable')" v-model="row.enabled"
                  :loading="row.loading" :active-value='true' :inactive-value='false' inline-prompt active-text="开启"
                  inactive-text="关闭" :before-change="() => onSetEnable(row)" />
                <template v-else>
                  <el-tag type="success" v-if="row.enabled">启用</el-tag>
                  <el-tag type="danger" v-else>禁用</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140" header-align="center" align="center" fixed="right">
              <template #default="{ row }">
                <el-button size="small" :type="isEditing(row) ? 'success' : 'primary'" @click="toggleEdit(row)">
                  {{ isEditing(row) ? '提交' : '编辑' }}
                </el-button>
                <my-dropdown-more v-auths="['api:industry:work-station:soft-delete']">
                  <template #dropdown>
                    <el-dropdown-menu>

                      <el-dropdown-item v-if="auth('api:industry:work-station:soft-delete')"
                        @click="cancelEdit(row)">取消</el-dropdown-item>
                      <el-dropdown-item v-if="auth('api:industry:work-station:soft-delete')"
                        @click="onWrite(row)">写入</el-dropdown-item>
                      <el-dropdown-item v-if="auth('api:industry:work-station:soft-delete')"
                        @click="onDelete(row)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </my-dropdown-more>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 10px">
            <el-pagination v-model:currentPage="state.pageInput.currentPage"
              v-model:page-size="state.pageInput.pageSize" :total="state.total" :page-sizes="[10, 20, 50, 100]" small
              background @size-change="onSizeChange" @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </el-card>
      </div>
    </pane>
    <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure"></MyFilterDialog>
    <plc-offset-dialog ref="plcOffsetDialogRef" @sure="onSureArgs"
      :title="state.blockOffsetFormTitle"></plc-offset-dialog>
    <BlockOffsetWriteForm ref="blockOffsetFormRef" :title="state.blcokOffsetWriteTitle"></BlockOffsetWriteForm>
  </MySplitPanes>
</template>
<script lang="ts" setup name="industry/plc-block">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent, computed } from 'vue'
import { PageInputBlockOffsetGetPageInput, BlockOffsetUpdateInput, BlockOffsetGetPageOutput, BlockOffsetGetOutput, PLCBlockGetOutput, SortInput, PLCBlockGetListOutput, PLCDataTypeEnum, PLCOffsetGetPageOutput } from '/@/api/industry/data-contracts'
import { BlockOffsetApi } from '/@/api/industry/BlockOffset'
import { Pane } from 'splitpanes'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable } from 'element-plus'

const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const StationBlockTableMenu = defineAsyncComponent(() => import('./compoents/station-block-table-menu.vue'))
const MySplitPanes = defineAsyncComponent(() => import('/@/components/my-layout/split-panes.vue'))
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))
const MyDropdownMore = defineAsyncComponent(() => import('/@/components/my-dropdown-more/index.vue'))
const PlcOffsetDialog = defineAsyncComponent(() => import('/@/views/industry/plc-offset/index.vue'))
const BlockOffsetWriteForm = defineAsyncComponent(() => import('./compoents/station-block-write-form.vue'))
const { proxy } = getCurrentInstance() as any
const getSortList = (data: { prop: string; order: any }) => {
  return [
    {
      propName: data.prop,
      order: data.order === 'ascending' ? 0 : data.order === 'descending' ? 1 : undefined,
    },
  ] as [SortInput]
}
const plcDataType = {
  0: 'BOOL',
  1: 'BYTE',
  2: 'WORD',
  3: 'DWORD',
  4: 'INT',
  5: 'DINT',
  6: 'REAL',
  7: 'LREAL',
  8: 'STRING'
} as const
const convertPLCDataTypeToLabel = (dataType: PLCDataTypeEnum) => plcDataType[dataType] as string;

const offsetAnthor = [
  {
    value: 'HeartToPlc',
    label: 'MES心跳',
  },
  {
    value: 'ReqQuery',
    label: '查询请求',
  },
  {
    value: 'ReqSave',
    label: '保存请求',
  },
  {
    value: 'ReqFormula',
    label: '配方请求',
  },
  {
    value: 'RepQuery',
    label: '查询回复',
  },
  {
    value: 'RepSave',
    label: '保存回复',
  },
  {
    value: 'RepFormula',
    label: '配方回复',
  },
  {
    value: 'ProductStatus',
    label: '产品总状态',
  },
  {
    value: 'QueryMasterCode',
    label: '查询主条码',
  },
  {
    value: 'SaveMasterCode',
    label: '保存主条码',
  },
  {
    value: 'ProductStatus',
    label: '产品总状态',
  },
  {
    value: 'Slot',
    label: '产品载体',
  },
  {
    value: 'FormulaOrder',
    label: '配方序号',
  }
]
const blockOffsetFormRef = ref()
const defalutSort = { prop: 'sort', order: 'ascending' }
const originalData: any = ref({})
const myFilterDialogRef = ref();
const plcOffsetDialogRef = ref()
const editingRowId = ref(0);
const state = reactive({
  loading: false,
  showQuery: true,
  blockOffsetFormTitle: '',
  blcokOffsetWriteTitle: '',
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    sortList: getSortList(defalutSort),
    filter: {
      getNewValue: false,
      workStationId: 0,
      plcBockId: 0,
      address: 0
    } as PLCBlockGetOutput,
    dynamicFilter: {},
  } as PageInputBlockOffsetGetPageInput,
  blockOffsetListData: [] as Array<BlockOffsetGetPageOutput>,
  filters: [
    {
      field: 'groupName',
      operator: 'Contains',
      description: '分组名称',
      componentName: 'el-input',
      defaultSelect: true,
    },
    {
      field: 'dataType',
      operator: 'Contains',
      description: '数据类型',
      componentName: 'el-input',
    },
    {
      field: 'another',
      operator: 'Contains',
      description: '别名',
      componentName: 'el-input',
    }
  ] as Array<DynamicFilterInfo>,
})
onMounted(async () => {
  eventBus.off('refreshBlockOffset')
  eventBus.on('refreshBlockOffset', async () => {
    onQuery()
  })
})
onBeforeMount(() => {
  eventBus.off('refreshBlockOffset')
})


const onSortChange = (data: { column: any; prop: string; order: any }) => {
  state.pageInput.sortList = getSortList(data)
  onQuery()
}
const onLook = async () => {
  state.pageInput.filter.getNewValue = true;
  onQuery();
  state.pageInput.filter.getNewValue = false;
}

//查询分页
const onQuery = async () => {
  state.loading = true
  const res = await new BlockOffsetApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })
  state.blockOffsetListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}
//高级查询
const onFilter = () => {
  myFilterDialogRef.value.open()
}

const onFilterSure = (dynamicFilter: any) => {
  state.pageInput.dynamicFilter = dynamicFilter
  onQuery()
}

//新增
const onAdd = () => {
  state.blockOffsetFormTitle = `选择数据块【${state.pageInput.filter?.address}】偏移量`
  plcOffsetDialogRef.value.open({ blockId: state.pageInput.filter?.blockId })
}

//修改
const onEdit = (row: BlockOffsetUpdateInput) => {
  editingRowId.value = editingRowId.value === row.id ? 0 : row.id;
  originalData[row.id] = { ...row };
}

const isEditing = (row: BlockOffsetUpdateInput) => {
  return editingRowId.value === row.id;
}
//写入
const onWrite = (row: BlockOffsetGetOutput) => {
  state.blcokOffsetWriteTitle = `写入【DB${state.pageInput.filter?.address}.${row.offset}】`
  blockOffsetFormRef.value.open({ blockOffsetId: row.id });
}
const cancelEdit = (row: any) => {
  const original = originalData[row.id];
  if (original) {
    Object.assign(row, original);
  }
  editingRowId.value = 0;
}
//确定任务参数
const onSureArgs = async (selectedIds: any) => {
  await new BlockOffsetApi().addMore({ plcOffsets: selectedIds, blockId: state.pageInput.filter?.blockId })
  onQuery();
}
const toggleEdit = (row: BlockOffsetUpdateInput) => {
  if (isEditing(row)) {
    onSaveEdit(row);
  } else {
    onEdit(row);
  }
}
const onSaveEdit = async (row: BlockOffsetUpdateInput) => {
  editingRowId.value = 0;
  if (row.id != undefined && row.id > 0) {
    await new BlockOffsetApi().update(row, { showSuccessMessage: true }).catch(() => {
    })
  }
  onQuery()
}
//删除
const onDelete = (row: BlockOffsetGetOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除数据块关联偏移量为【${row.offset}】?`)
    .then(async () => {
      await new BlockOffsetApi().softDelete({ id: row.id }, { loading: true, showSuccessMessage: true })
      onQuery()
    })
    .catch(() => { })
}
//启用或禁用
const onSetEnable = (row: BlockOffsetGetOutput & { loading: boolean }) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要${row.enabled ? '禁用' : '启用'}偏移量为：【${row.offset}】?`)
      .then(async () => {
        row.loading = true
        const res = await new BlockOffsetApi()
          .setEnable({ blockOffsetId: row.id, enabled: !row.enabled }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
            row.loading = false
          })
        if (res && res.success) {
          resolve(true)
        } else {
          reject(new Error('Cancel'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}

//启用或禁用
const onSetNotice = (row: BlockOffsetGetOutput & { loading: boolean }) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要${row.isNoticed ? '停止' : '启用'}订阅偏移量为：【${row.offset}】?`)
      .then(async () => {
        row.loading = true
        const res = await new BlockOffsetApi()
          .setNotice({ blockOffsetId: row.id, noticed: !row.isNoticed }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
            row.loading = false
          })
        if (res && res.success) {
          resolve(true)
        } else {
          reject(new Error('Cancel'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}


const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}
const onPlcBlockTableClick = (tableRow: PLCBlockGetListOutput | null) => {
  if (state.pageInput.filter) {
    state.pageInput.filter.blockId = tableRow?.id
    state.pageInput.filter.stationId = tableRow?.workStationId
    state.pageInput.filter.address = tableRow?.address
  }
  onQuery()
}
</script>
<style scoped lang="scss"></style>
